package com.tulingxueyuan.mall.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tulingxueyuan.mall.common.api.CommonResult;
import com.tulingxueyuan.mall.common.exception.ApiException;
import com.tulingxueyuan.mall.componet.TradePayProp;
import com.tulingxueyuan.mall.config.AlipayConfig;
import com.tulingxueyuan.mall.dto.ConfirmOrderDTO;
import com.tulingxueyuan.mall.dto.OrderDetailDTO;
import com.tulingxueyuan.mall.dto.OrderListDTO;
import com.tulingxueyuan.mall.dto.OrderParamDTO;
import com.tulingxueyuan.mall.modules.oms.model.OmsOrder;
import com.tulingxueyuan.mall.modules.oms.service.OmsOrderService;
import com.tulingxueyuan.mall.modules.oms.service.TradeService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/order")
@Api(tags = "OrderController" ,description = "下单")
public class OrderController {
    @Autowired
    OmsOrderService orderService;
    @Autowired
    TradeService tradeService;
    @Autowired
    TradePayProp  tradePayProp;

    /**
     * 加入购物车---》生成确认订单信息
     * 直接购买--  productid  skuid
     * 初始化确认订单的商品信息
     *  .post(
     *           "/order/generateConfirmOrder",
     *           Qs.stringify({ itemIds: constStore.itemids }, { indices: false }),
     *           { headers: { "Content-Type": "application/x-www-form-urlencoded" } }
     *         )
     */
    @RequestMapping(value = "/generateConfirmOrder", method = RequestMethod.POST)
    public CommonResult generateConfirmOrder(@RequestParam("itemIds") List<Long> ids) {

     ConfirmOrderDTO  confirmOrderDTO = orderService.generateConfirmOrder(ids);
        return CommonResult.success(confirmOrderDTO);
    }
    /**
     * 生成订单（下单）
     *  .post("/order/generateOrder", {
     *             itemIds: this.itemIds,     // 购物id
     *             memberReceiveAddressId: item.id,  // 地址id
     *             //payType: 1,   // 支付宝
     *           })
     */
    @RequestMapping(value = "/generateOrder", method = RequestMethod.POST)
    public CommonResult generateOrder(@RequestBody OrderParamDTO paramDTO) {

        OmsOrder omsOrder = orderService.generateOrder(paramDTO);
        return CommonResult.success(omsOrder.getId());


    }
    /**
     * 读取下单成功后的订单详情
     *   this.axios.get(`/order/orderDetail?orderId=${this.orderId}`).then((res)=>{
     */
    @RequestMapping(value = "/orderDetail", method = RequestMethod.GET)
    public CommonResult getOrderDetail(@RequestParam("orderId") Long id) {

        OrderDetailDTO orderDetailDTO = orderService.orderDetail(id);
        return CommonResult.success(orderDetailDTO);

    }
    /**
     * 我的订单列表
     * this.axios.post('/order/list/userOrder',Qs.stringify({
     *             pageSize:10,
     *             pageNum:this.pageNum
     *
     *         }
     */


    @RequestMapping(value = "/list/userOrder", method = RequestMethod.POST)
    public CommonResult getMyOrders(@RequestParam(defaultValue = "10",value = "pageSize") Integer pageSize,
                                    @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum) {

        IPage<OrderListDTO> list = orderService.getMyOrders(pageSize,pageNum);
        return CommonResult.success(list);


    }

    /**
     * 生成支付宝当面付二维码
     *  this.axios.post('/order/tradeQrCode',Qs.stringify({
     *           orderId:this.orderId,
     *           payType:1
     */
    @ApiOperation("获取支付宝二维码,当前只实现支付宝")
    @ApiImplicitParams({@ApiImplicitParam(name = "orderId" ,value = "订单id"),
                        @ApiImplicitParam(name = "payType",value = "支付类型 1 ：支付宝，2:微信")})
    @RequestMapping(value = "/tradeQrCode",method = RequestMethod.POST)
    public CommonResult tradeQrCode(@RequestParam("orderId") Long orderId,
                                    @RequestParam("payType") Integer payType) {

        if(payType > 2 || payType  < 0) {
            throw  new ApiException("支付类型参数错误！");
        }

        return tradeService.tradeQrCode(orderId,payType);
    }


    /**
     *
     * @param request
     * @param response
     * @throws UnsupportedEncodingException
     * @throws AlipayApiException
     */
    @RequestMapping(value = "/paySuccess/{payType}", method = RequestMethod.POST)
    public void getMyOrders(
            @PathVariable("payType") Integer payType,
            HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, AlipayApiException {


        System.out.println("支付成功");

        /**
         * 5.更新订单状态和支付方式
         * 6.清除锁定库存，扣除实际库存
         * 7.删除二维码
         */


        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            if(!name.toLowerCase().equals("sign_type")) {
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
        }

        String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkpuW8kXP/S6KB9gfS+F1l8wEL3x59KX6m32BeaoBR5CQO3Xao02FQknKcocUhVvNtxx6NcQbsVgBvCrpfFIYc0cNPbjfSLeyNoEZmf/6CUM625xZe8NawGaZt8KJuNk5ARQc6ircpcZS5U98kBGmop3Fr8ONbBz/ogMefq43z7Kcrj79PBM0NsaY13bEIeCDfoRzp7YcUzK/lPI7UZPicPEKNHzjLTU6I5KfjU+W7OpB1k5hMnomYHuW+AZy4bax6Gihhf7WEbcjYr9NTfN5daLNxcb/v7HsHE34BDBxYvynXgtxxyLED2UtMrnD9lAhqtK7MV2po3B993sdwcRCzQIDAQAB";
        // 验签  ：去除sign和sign_type 参数 进行验签， checkV1 会在方法中去除，CheckV2不会去除sign_type，所以要手动排除
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipay_public_key, "utf-8","RSA2"); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            // 订单id
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            if(StrUtil.isNotBlank(out_trade_no) && NumberUtil.isNumber(out_trade_no)){
                Long orderId=Long.parseLong(out_trade_no);
                orderService.paySuccess(orderId,payType);
                log.info("支付成功");
            }

        }else {
            System.out.println("验签失败");
        }

    }

}
